package com.example.application.xiti;
import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.content.FileProvider;


import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.example.application.FileUtil;
import com.example.application.MyApp;
import com.example.application.R;
import com.example.application.activity.MainActivity;

public class LoginActivity extends AppCompatActivity {

    private AppCompatEditText usernameEditText;
    private AppCompatEditText passwordEditText;
    private AppCompatButton loginButton;
    private AppCompatButton cameraButton;
    private AppCompatButton camera1Button;
    private AppCompatButton cropButton;
    private AppCompatButton movieButton;
    private AppCompatButton movie1Button;
    private AppCompatImageView mainImageView;
    private VideoView mainVideoView;



    private File file;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        usernameEditText = findViewById(R.id.usernameEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        loginButton = findViewById(R.id.loginButton);
        cameraButton = findViewById(R.id.cameraButton);
        mainImageView = findViewById(R.id.mainImageView);
        camera1Button = findViewById(R.id.camera1Button);
        cropButton = findViewById(R.id.cropButton);
        movieButton = findViewById(R.id.movieButton);
        movie1Button = findViewById(R.id.movie1Button);
        mainVideoView = findViewById(R.id.mainVideoView);


/*
        ArrayList<String>files=getFilesAllName("/storage/emulated/0/Movies");
        for (int i=0;i<files.size();i++){
            if (files.get(i).contains(".mp4")){
                File file=new File(files.get(i));
                mainVideoView.setVideoView.start();
                break;
            }
*/

        String key = MyApp.get().getSharedPreferences().getString("key", "");
        if (!key.isEmpty()) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        loginButton.setOnClickListener(view -> {
            String mobile = usernameEditText.getText().toString();
            String password = passwordEditText.getText().toString();
            if (mobile.isEmpty()) {
                Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!isMobileNO(mobile)) {
                Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.isEmpty()) {
                Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.length() < 6) {
                Toast.makeText(this, "请输入有效的密码", Toast.LENGTH_SHORT).show();
                return;
            }
            OkGo.<String>post("https://demo.shopwt.com/api/mobile/index.php?w=login")
                    .params("username", mobile)
                    .params("password", password)
                    .params("client", "wap")
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body().toString());
                                if (jsonObject.getInt("code") == 400) {
                                    jsonObject = jsonObject.getJSONObject("datas");
                                    Toast.makeText(LoginActivity.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                jsonObject = jsonObject.getJSONObject("datas");
                                String key = jsonObject.getString("key");
                                MyApp.get().getEditor().putString("key", key).apply();
                                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        });

        cameraButton.setOnClickListener(view -> {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 999);
        });

        camera1Button.setOnClickListener(view -> {
            file = FileUtil.createFile(getExternalMediaDirs()[0].getAbsolutePath(), "application", "JPG");
            if (file != null) {
                Uri uri = FileProvider.getUriForFile(this, "com.example.application.fileProvider", file);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, 1000);
            }
        });

        cropButton.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("video/*");
            startActivityForResult(intent, 1001);
        });

        movie1Button.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("video/*");
            startActivityForResult(intent, 1003);
        });

        //打开相机录制视频并播放
        movie1Button.setOnClickListener(view -> {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            startActivityForResult(intent, 1004);
        });
    }

    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();
    }

    @Override
    public void onResume() {
        super.onResume();
        XXPermissions.with(this).permission(getPermissions1()).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {

            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                //权限被拒绝或者部分权限未完整授权
                Log.d("TAGS", "123");
            }
        });
    }

    private String[] getPermissions1() {

        return new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CAMERA,//拍照权限
                Manifest.permission.READ_EXTERNAL_STORAGE,//读外部存储
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//写外部存储
        };

    }

    private ArrayList<String> getFilesAllName(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null) {
            return null;
        }
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            list.add(files[i].getAbsolutePath());
        }
        return list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 999) {
                Bitmap bitmap = data.getExtras().getParcelable("data");
                mainImageView.setImageBitmap(bitmap);
            }
            if (requestCode == 1000) {
                Log.d("TAGS", file.getAbsolutePath());
                mainImageView.setImageURI(Uri.fromFile(file));
            }
            if (requestCode == 1001) {
                file = FileUtil.createFile(
                        getExternalCacheDirs()[0].getAbsolutePath(),
                        "application", "jpg");
                Intent cropIntent = new Intent("com.android.camera.action.CROP");
                cropIntent.setDataAndType(data.getData(), "image/*");
                cropIntent.putExtra("crop", "true");
                cropIntent.putExtra("aspectX", "1");
                cropIntent.putExtra("aspectY", "1");
                cropIntent.putExtra("outputX", "500");
                cropIntent.putExtra("outputY", "500");
                cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + file.getAbsolutePath()));
                cropIntent.putExtra("return-data", "false");
                startActivityForResult(cropIntent, 1002);
                FileUtil.showInAlbum(this, file.getAbsolutePath());
            }
            if (requestCode == 1002) {
                mainImageView.setImageURI(Uri.fromFile(file));
            }
            if (requestCode == 1003) {
                Uri uri = data.getData();
                mainVideoView.setVideoURI(uri);
                mainVideoView.start();
            }
            if (requestCode == 1004) {
                Uri uri = data.getData();
                mainVideoView.setVideoURI(uri);
                mainVideoView.start();
            }

        }
    }
}